﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace asMeishi.web.Models
{
    using Classes;
    public class dict : MongoDocument
    {
        //这个bug?直接让Dictionary:value在最尾部．为null时．在读下一条dict时．无法将mongodb.document转为对应实体类型
        public Dictionary<string, string> value { get; set; }
        
        public string name { get; set; }


    }

    public class dictClass
    {
        public static Dictionary<string, string> get(string name)
        {
            DataSession<MongoDataContext, dict> sess = new DataSession<MongoDataContext, dict>();
            var re = sess.Where(d => d.name == name).FirstOrDefault();
            if (re == null) throw new asMeishiException("字典 " + name + " 未创建！");
            if (re.value == null || !re.value.Any()) throw new asMeishiException("字典 " + name + " 无内容！");

            return re.value;
        }

        public static string getStr(string name, string val)
        {
            if (string.IsNullOrWhiteSpace(val)) return "";
            string[] re = val.Split(',');
            var dict = get(name);
            for (int i = 0; i < re.Length; i++)
            {
                string _re = re[i].Trim();
                if (!string.IsNullOrWhiteSpace(_re))
                {
                    try
                    {
                        re[i] = dict[re[i].Trim()];
                    }
                    catch (Exception)
                    {
                        re[i] = "字典中未定义";
                    }
                }
            }
            return string.Join(",", re);
        }
    }

}
